#!/bin/bash

# 环境检查与WeBASE部署一体化脚本（修复版）
# 支持CentOS 7.2+ 和 Ubuntu 16.04+
# 作者：Atanycosts
# 版本：2.2
# 更新说明：
# 1. 修复目录移动冲突问题
# 2. 增强目录清理逻辑
# 3. 改进错误处理机制

# 日志文件配置
LOG_FILE="webase_deploy.log"
echo "WeBASE 部署日志 - $(date)" > $LOG_FILE

# 定义颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 预设代理配置
DEFAULT_PROXY="http://8.219.157.143:8888"
# 预下载文件配置
DOWNLOAD_PREFIX="https://atanycosts.cn/file/path"
PRE_DOWNLOAD_FILES=(
    "webase-node-mgr.zip"
    "webase-web.zip"
    "webase-web-mobile.zip"
    "fisco-bcos.tar.gz"
    "webase-sign.zip"
    "webase-front.zip"
)
DOWNLOAD_DIR="downloads"

# 显示 ASCII 艺术
show_ascii_art() {
    echo -e "${GREEN}"
    cat << "EOF"
  ______     __                                                                    __              
 /      \   /  |                                                                  /  |             
/$$$$$$  | _$$ |_     ______   _______   __    __   _______   ______    _______  _$$ |_    _______ 
$$ |__$$ |/ $$   |   /      \ /       \ /  |  /  | /       | /      \  /       |/ $$   |  /       |
$$    $$ |$$$$$$/    $$$$$$  |$$$$$$$  |$$ |  $$ |/$$$$$$$/ /$$$$$$  |/$$$$$$$/ $$$$$$/  /$$$$$$$/ 
$$$$$$$$ |  $$ | __  /    $$ |$$ |  $$ |$$ |  $$ |$$ |      $$ |  $$ |$$      \   $$ | __$$      \ 
$$ |  $$ |  $$ |/  |/$$$$$$$ |$$ |  $$ |$$ \__$$ |$$ \_____ $$ \__$$ | $$$$$$  |  $$ |/  |$$$$$$  |
$$ |  $$ |  $$  $$/ $$    $$ |$$ |  $$ |$$    $$ |$$       |$$    $$/ /     $$/   $$  $$//     $$/ 
$$/   $$/    $$$$/   $$$$$$$/ $$/   $$/  $$$$$$$ | $$$$$$$/  $$$$$$/  $$$$$$$/     $$$$/ $$$$$$$/  
                                        /  \__$$ |                                                 
                                        $$    $$/                                                  
                                         $$$$$$/               
EOF
    echo -e "${NC}"
}
# 检查是否为 root 用户
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo -e "${YELLOW}当前用户不是 root，尝试使用 sudo 重新运行脚本...${NC}" | tee -a $LOG_FILE
        exec sudo "$0" "$@"
        exit 1
    fi
}

# 检查操作系统
check_os() {
    echo -e "${BLUE}检测操作系统...${NC}" | tee -a $LOG_FILE
    if [ -f /etc/centos-release ]; then
        OS_TYPE="centos"
    elif [ -f /etc/lsb-release ]; then
        OS_TYPE="ubuntu"
    else
        echo -e "${RED}不支持的操作系统！请使用CentOS 7.2+或Ubuntu 16.04+。${NC}" | tee -a $LOG_FILE
        exit 1
    fi
    echo -e "${GREEN}操作系统类型：${OS_TYPE}${NC}" | tee -a $LOG_FILE
}

# 检查并安装依赖
install_dependencies() {
    echo -e "${BLUE}检查并安装基础依赖...${NC}" | tee -a $LOG_FILE
    local dependencies=("openssl" "curl" "wget" "git" "unzip" "tree")
    for dep in "${dependencies[@]}"; do
        if ! command -v $dep &> /dev/null; then
            echo -e "${YELLOW}${dep} 未安装，正在安装...${NC}" | tee -a $LOG_FILE
            if [ "$OS_TYPE" == "centos" ]; then
                yum install -y $dep >> $LOG_FILE 2>&1
            else
                apt-get install -y $dep >> $LOG_FILE 2>&1
            fi
            echo -e "${GREEN}${dep} 安装完成${NC}" | tee -a $LOG_FILE
        else
            echo -e "${GREEN}${dep} 已安装${NC}" | tee -a $LOG_FILE
        fi
    done
}

# 安装和配置Java
install_java() {
    echo -e "${BLUE}检查Java环境...${NC}" | tee -a $LOG_FILE
    if ! command -v java &> /dev/null; then
        echo -e "${YELLOW}正在安装JDK 8u191...${NC}" | tee -a $LOG_FILE
        wget http://atanycosts.cn/file/path/jdk-8u191.tar.gz -O /tmp/jdk-8u191.tar.gz >> $LOG_FILE 2>&1
        tar -zxvf /tmp/jdk-8u191.tar.gz -C /usr/local/ >> $LOG_FILE 2>&1
        echo "export JAVA_HOME=/usr/local/jdk1.8.0_191" >> /etc/profile
        echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> /etc/profile
        source /etc/profile
        echo -e "${GREEN}JDK 8u191 安装完成${NC}" | tee -a $LOG_FILE
    else
        echo -e "${GREEN}Java已安装，版本信息：${NC}" | tee -a $LOG_FILE
        java -version | tee -a $LOG_FILE
    fi
}

# 安装和配置MySQL
install_mysql() {
    echo -e "${BLUE}检查MySQL环境...${NC}" | tee -a $LOG_FILE
    if ! command -v mysql &> /dev/null; then
        echo -e "${YELLOW}正在安装MySQL...${NC}" | tee -a $LOG_FILE
        if [ "$OS_TYPE" == "centos" ]; then
            wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm >> $LOG_FILE 2>&1
            rpm -ivh mysql57-community-release-el7-11.noarch.rpm >> $LOG_FILE 2>&1
            yum install -y mysql-community-server >> $LOG_FILE 2>&1
            systemctl start mysqld >> $LOG_FILE 2>&1
            systemctl enable mysqld >> $LOG_FILE 2>&1
        else
            apt-get install -y mysql-server >> $LOG_FILE 2>&1
            systemctl start mysql >> $LOG_FILE 2>&1
            systemctl enable mysql >> $LOG_FILE 2>&1
        fi
        echo -e "${GREEN}MySQL 安装完成${NC}" | tee -a $LOG_FILE
    else
        echo -e "${GREEN}MySQL已安装，版本信息：${NC}" | tee -a $LOG_FILE
        mysql --version | tee -a $LOG_FILE
    fi

    # 获取MySQL主版本号
    MYSQL_VER=$(mysql -V | awk '{print $5}' | awk -F'.' '{print $1}')
    echo -e "${BLUE}检测到MySQL主版本：${MYSQL_VER}${NC}" | tee -a $LOG_FILE

    # 配置root密码并验证
    echo -e "${YELLOW}正在配置MySQL root密码...${NC}" | tee -a $LOG_FILE
    mysql -uroot -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';" >/dev/null 2>&1 || {
        echo -e "${YELLOW}检测到旧版MySQL，使用传统密码设置方式...${NC}" | tee -a $LOG_FILE
        mysql -uroot -e "UPDATE mysql.user SET authentication_string=password('root') WHERE User='root';"
        mysql -uroot -e "UPDATE mysql.user SET plugin='mysql_native_password' WHERE User='root';"
    }
    
    # 验证密码是否生效
    echo -e "${YELLOW}验证数据库密码...${NC}" | tee -a $LOG_FILE
    if ! mysql -uroot -proot -e "SELECT 1;" >/dev/null 2>&1; then
        echo -e "${RED}错误：无法用新密码登录MySQL，请检查配置！${NC}" | tee -a $LOG_FILE
        exit 1
    fi
    echo -e "${GREEN}MySQL root密码验证通过${NC}" | tee -a $LOG_FILE

    mysql -uroot -proot -e "FLUSH PRIVILEGES;" | tee -a $LOG_FILE
}

# 安装Python环境
install_python() {
    echo -e "${BLUE}检查Python环境...${NC}" | tee -a $LOG_FILE
    if ! command -v python3 &> /dev/null; then
        echo -e "${YELLOW}正在安装Python3...${NC}" | tee -a $LOG_FILE
        if [ "$OS_TYPE" == "centos" ]; then
            yum install -y python3 python3-pip >> $LOG_FILE 2>&1
        else
            apt-get install -y python3 python3-pip >> $LOG_FILE 2>&1
        fi
        echo -e "${GREEN}Python3 安装完成${NC}" | tee -a $LOG_FILE
    else
        echo -e "${GREEN}Python3已安装，版本信息：${NC}" | tee -a $LOG_FILE
        python3 --version | tee -a $LOG_FILE
    fi

    echo -e "${BLUE}检查并安装PyMySQL...${NC}" | tee -a $LOG_FILE
    if ! python3 -c "import pymysql" &> /dev/null; then
        echo -e "${YELLOW}正在安装PyMySQL...${NC}" | tee -a $LOG_FILE
        pip3 install PyMySQL >> $LOG_FILE 2>&1
        echo -e "${GREEN}PyMySQL 安装完成${NC}" | tee -a $LOG_FILE
    else
        echo -e "${GREEN}PyMySQL 已安装${NC}" | tee -a $LOG_FILE
    fi
}

# 预下载提示
pre_download_prompt() {
    echo -e "${CYAN}============================== 预下载提示 =============================="
    echo -e "为加速部署过程，建议提前下载以下文件到当前目录的${DOWNLOAD_DIR}/目录："
    for file in "${PRE_DOWNLOAD_FILES[@]}"; do
        echo -e "${YELLOW}${DOWNLOAD_PREFIX}/${file}${NC}"
    done
    echo -e "=======================================================================${NC}"
    
    read -p "是否希望脚本自动下载这些文件？(y/n) [n]: " auto_download
    if [[ $auto_download =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}开始创建下载目录...${NC}" | tee -a $LOG_FILE
        mkdir -p $DOWNLOAD_DIR
        cd $DOWNLOAD_DIR || exit 1
        
        echo -e "${BLUE}开始下载加速文件（显示进度条）...${NC}" | tee -a $LOG_FILE
        for file in "${PRE_DOWNLOAD_FILES[@]}"; do
            echo -e "${YELLOW}正在下载：${file}...${NC}" | tee -a $LOG_FILE
            wget --progress=bar:force "${DOWNLOAD_PREFIX}/${file}" -O "${file}" 2>&1 | tee -a $LOG_FILE
            if [ ! -s "${file}" ]; then
                echo -e "${RED}错误：${file} 下载失败，请检查网络连接！${NC}" | tee -a $LOG_FILE
                exit 1
            fi
            echo -e "${GREEN}${file} 下载完成${NC}" | tee -a $LOG_FILE
        done
        cd ..
    else
        echo -e "${YELLOW}请手动将文件放置到 ${DOWNLOAD_DIR}/ 目录后继续...${NC}" | tee -a $LOG_FILE
        read -p "按Enter键继续..." </dev/tty
    fi
}

# 清理部署目录
clean_deploy_dir() {
    local target_dir=$1
    if [ -d "$target_dir" ]; then
        echo -e "${YELLOW}检测到已存在的部署目录，正在清理...${NC}" | tee -a $LOG_FILE
        rm -rf "$target_dir"/*  # 只清理内容，保留目录
        echo -e "${GREEN}目录清理完成${NC}" | tee -a $LOG_FILE
    else
        mkdir -p "$target_dir"
    fi
}

# 代理设置功能
setup_proxy() {
    echo -e "${CYAN}请选择代理配置："
    echo -e "1) 使用预设代理（${DEFAULT_PROXY}）"
    echo -e "2) 自定义代理"
    echo -e "3) 不使用代理"
    read -p "请选择[1-3] (默认3): " proxy_choice

    case ${proxy_choice:-3} in
        1)
            export http_proxy=$DEFAULT_PROXY
            export https_proxy=$DEFAULT_PROXY
            echo -e "${GREEN}使用预设代理：${DEFAULT_PROXY}${NC}" | tee -a $LOG_FILE
            ;;
        2)
            read -p "请输入代理地址（格式：IP:PORT）: " custom_proxy
            export http_proxy="http://${custom_proxy}"
            export https_proxy="http://${custom_proxy}"
            echo -e "${GREEN}使用自定义代理：http://${custom_proxy}${NC}" | tee -a $LOG_FILE
            ;;
        3)
            unset http_proxy https_proxy
            echo -e "${GREEN}不使用代理${NC}" | tee -a $LOG_FILE
            ;;
        *)
            echo -e "${RED}无效选择，默认不使用代理${NC}" | tee -a $LOG_FILE
            unset http_proxy https_proxy
            ;;
    esac
}

# 部署WeBASE
deploy_webase() {
    echo -e "${BLUE}===== 开始部署WeBASE ====="${NC} | tee -a $LOG_FILE
    
    # 下载部署包（带进度条）
    echo -e "${YELLOW}下载WeBASE部署包...${NC}" | tee -a $LOG_FILE
    if ! wget --progress=bar:force https://github.com/WeBankBlockchain/WeBASELargeFiles/releases/download/v1.5.5/webase-deploy.zip -O webase-deploy.zip 2>&1 | tee -a $LOG_FILE; then
        echo -e "${YELLOW}主仓库下载失败，尝试Gitee镜像...${NC}" | tee -a $LOG_FILE
        wget --progress=bar:force https://gitee.com/WeBank/WeBASE/releases/download/v1.5.5/webase-deploy.zip -O webase-deploy.zip 2>&1 | tee -a $LOG_FILE
    fi

    # 验证文件完整性
    echo -e "${YELLOW}验证压缩包完整性...${NC}" | tee -a $LOG_FILE
    if [ ! -s webase-deploy.zip ]; then
        echo -e "${RED}错误：下载的压缩包为空，请检查网络连接！${NC}" | tee -a $LOG_FILE
        exit 1
    fi
    if ! unzip -t webase-deploy.zip >> $LOG_FILE 2>&1; then
        echo -e "${RED}错误：压缩包损坏，请重新下载！${NC}" | tee -a $LOG_FILE
        exit 1
    fi

    # 清理并准备部署目录
    clean_deploy_dir "webase-deploy"

    # 解压部署包到临时目录
    echo -e "${YELLOW}解压部署包到临时目录...${NC}" | tee -a $LOG_FILE
    TEMP_DIR=$(mktemp -d)
    unzip -o webase-deploy.zip -d "$TEMP_DIR" >> $LOG_FILE 2>&1 || {
        echo -e "${RED}解压失败，请检查磁盘空间或文件权限！${NC}" | tee -a $LOG_FILE
        rm -rf "$TEMP_DIR"
        exit 1
    }

    # 处理嵌套目录问题
    if [ -d "$TEMP_DIR/webase-deploy" ]; then
        echo -e "${YELLOW}检测到嵌套目录结构，正在处理...${NC}" | tee -a $LOG_FILE
        mv "$TEMP_DIR/webase-deploy"/* webase-deploy/
    else
        mv "$TEMP_DIR"/* webase-deploy/
    fi
    rm -rf "$TEMP_DIR"

    # 复制预下载文件
    if [ -d "$DOWNLOAD_DIR" ]; then
        echo -e "${BLUE}开始复制预下载文件...${NC}" | tee -a $LOG_FILE
        cp "$DOWNLOAD_DIR"/webase-node-mgr.zip webase-deploy/
        cp "$DOWNLOAD_DIR"/webase-web.zip webase-deploy/
        cp "$DOWNLOAD_DIR"/webase-web-mobile.zip webase-deploy/
        cp "$DOWNLOAD_DIR"/fisco-bcos.tar.gz webase-deploy/
        cp "$DOWNLOAD_DIR"/webase-sign.zip webase-deploy/
        cp "$DOWNLOAD_DIR"/webase-front.zip webase-deploy/
        echo -e "${GREEN}所有预下载文件已复制到部署目录${NC}" | tee -a $LOG_FILE
    else
        echo -e "${YELLOW}未检测到预下载目录，将从网络下载所需文件${NC}" | tee -a $LOG_FILE
    fi

    # 进入部署目录
    cd webase-deploy || {
        echo -e "${RED}无法进入部署目录，请检查！${NC}" | tee -a $LOG_FILE
        exit 1
    }

    # 配置文件修改提示
    echo -e "${CYAN}请按以下说明修改配置文件："
    echo -e "1. 修改common.properties中的数据库配置"
    echo -e "   mysql.ip=localhost"
    echo -e "   mysql.port=3306"
    echo -e "   mysql.user=root"
    echo -e "   mysql.password=root"
    echo -e "2. 检查节点配置与本地环境是否一致"
    echo -e "按Enter键继续..."${NC}
    read -r

    # 执行部署
    echo -e "${BLUE}开始执行部署...${NC}" | tee -a $LOG_FILE
    python3 deploy.py installAll 2>&1 | tee -a $LOG_FILE

    if [ $? -eq 0 ]; then
        echo -e "${GREEN}====== 部署成功！ ======"${NC} | tee -a $LOG_FILE
        echo -e "管理平台访问地址：http://服务器IP:5000"
    else
        echo -e "${RED}====== 部署失败，请检查日志：${LOG_FILE} ======"${NC} | tee -a $LOG_FILE
        exit 1
    fi
}

# 主函数
main() {
    show_ascii_art
    pre_download_prompt
    check_root
    check_os
    install_dependencies
    setup_proxy
    install_java
    install_mysql
    install_python
    deploy_webase
    
    echo -e "\n${MAGENTA}感谢使用！更多技术分享请访问："
    echo -e "B站主页：https://space.bilibili.com/499719031"
    echo -e "2694420747@qq.com${NC}"
}

# 执行主函数
main


